package com.huopaolan.yohuoshop.Mvp.View.Activity;

import android.annotation.SuppressLint;
import android.content.ContentValues;
import android.content.Intent;
import android.graphics.Color;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.huopaolan.lib_core.Base.BaseActivity;
import com.huopaolan.yohuoshop.Bean.UserEntity;
import com.huopaolan.yohuoshop.Dao.Service.DBService;
import com.huopaolan.yohuoshop.Di.Compont.DaggerLoginCompont;
import com.huopaolan.yohuoshop.Di.Modules.LoginModules;
import com.huopaolan.yohuoshop.Mvp.Contract.UserContract;
import com.huopaolan.yohuoshop.Mvp.Presenter.LoginPresenter;
import com.huopaolan.yohuoshop.R;
import com.huopaolan.yohuoshop.Sp.SpUtils;
import com.umeng.socialize.UMAuthListener;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.bean.SHARE_MEDIA;

import org.greenrobot.eventbus.EventBus;

import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

public class LoginActivity extends BaseActivity<LoginPresenter> implements UserContract.LoginIView, OnClickListener, UMAuthListener {
    private TextView register_activity;
    private EditText user_phone, user_code, user_username, user_password;
    private Button login_button;
    private TextView auth_code, open_code;
    private ImageView image_cancel, image_weibo;
    private LinearLayout linear_password, linear_phone;
    private boolean flag = true;
    private int numcode;
    private int times = 5;
    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 100) {
                numcode = (int) ((Math.random() * 9 + 1) * 100000);
                auth_code.setText("" + numcode);
            }
        }
    };

    @Override
    public int layoutID() {
        return R.layout.activity_user_login;
    }

    @Override
    public void initView() {
        //初始化
        register_activity = findViewById(R.id.tv_login_register);
        register_activity.setOnClickListener(this);
        user_phone = findViewById(R.id.et_login_phone_zh);
        user_code = findViewById(R.id.et_login_phone_yzm);
        login_button = findViewById(R.id.btn_login_login);
        auth_code = findViewById(R.id.iv_login_yzm_get);
        open_code = findViewById(R.id.tv_login_type);
        user_username = findViewById(R.id.et_login_y_zh);
        user_password = findViewById(R.id.et_login_y_pawd);
        linear_password = findViewById(R.id.ll_y);
        linear_phone = findViewById(R.id.ll_phone);
        image_cancel = findViewById(R.id.iv_login_black);
        image_weibo = findViewById(R.id.iv_login_weibo);
        image_weibo.setOnClickListener(this);
        image_cancel.setOnClickListener(this);
        auth_code.setOnClickListener(this);
        open_code.setOnClickListener(this);
    }

    @Override
    protected void onStart() {
        Window window = getWindow();
        window.setStatusBarColor(Color.BLACK);
        super.onStart();
    }

    @Override
    public void initData() {
        login_button.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                final String phone = user_phone.getText().toString();
                final String code = user_code.getText().toString();
                String user_name = user_username.getText().toString();
                String user_pass = user_password.getText().toString();
                Toast.makeText(LoginActivity.this, "" + flag, Toast.LENGTH_SHORT).show();
                if (flag) {
                    if (TextUtils.isEmpty(phone)) {
                        Toast.makeText(LoginActivity.this, "手机号不能为空", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    if (TextUtils.isEmpty(code)) {
                        Toast.makeText(LoginActivity.this, "验证码不能为空", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    if (Integer.parseInt(code) == numcode)
                        p.LoginRequest(phone, "123456");
                } else {
                    if (TextUtils.isEmpty(user_name)) {
                        Toast.makeText(LoginActivity.this, "手机号不能为空", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    if (TextUtils.isEmpty(user_pass)) {
                        Toast.makeText(LoginActivity.this, "密码不能为空", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    p.LoginRequest(user_name, user_pass);
                }
            }
        });
    }

    @Override
    public void setUpDagger() {
        DaggerLoginCompont.builder()
                .loginModules(new LoginModules(this))
                .build().inject(this);
    }

    @Override
    public void LoginSuccess(UserEntity entity) {
//        Toast.makeText(this, "" + entity.values.get(0).nick_name, Toast.LENGTH_SHORT).show();
        if (TextUtils.equals(entity.msg, "请求失败")) {
            Toast.makeText(this, "该账号未注册", Toast.LENGTH_SHORT).show();
            return;
        }
        DBService.getDbService().delete("User", null, null);
        //存入数据库
        ContentValues values = new ContentValues();
        values.put("user_id", entity.values.get(0).user_id);
        values.put("nick_name", entity.values.get(0).nick_name);
        values.put("user_name", entity.values.get(0).user_name);
        values.put("user_pwd", entity.values.get(0).user_pwd);
        values.put("user_sex", entity.values.get(0).user_sex);
        values.put("user_birthday", entity.values.get(0).user_birthday);
        values.put("user_height", entity.values.get(0).user_height);
        values.put("user_weight", entity.values.get(0).user_weight);
        values.put("user_head", entity.values.get(0).user_head);
        long user = DBService.getDbService().insert("User", values);
        if (user > 0) {
            Log.d("DBService", "数据库储存成功");
            DBService.getDbService().close();
            EventBus.getDefault().post(entity.values.get(0).user_id);
            SpUtils.getInstance().SpWrite(true);
            finish();
        } else {
            Log.d("DBService", "数据库储存失败");
        }
    }

    @Override
    public void showDialog() {

    }

    @Override
    public void hideDialog() {

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_login_register:
                startActivity(new Intent(this, RegisterActivity.class));
                finish();
                break;
            case R.id.iv_login_yzm_get:
                Timer timer = new Timer();
                timer.schedule(new TimerTask() {
                    @Override
                    public void run() {
                        while (times > 0) {
                            times--;
                            if (times == 0) {
                                handler.sendEmptyMessage(100);
                            }
                        }
                    }
                }, 1000);
                auth_code.setText("" + times);
                break;
            case R.id.tv_login_type:
                if (flag) {
                    linear_phone.setVisibility(View.GONE);
                    linear_password.setVisibility(View.VISIBLE);
                    open_code.setText("账号密码登录");
                    flag = false;
                } else {
                    linear_password.setVisibility(View.GONE);
                    linear_phone.setVisibility(View.VISIBLE);
                    open_code.setText("手机验证码登录");
                    flag = true;
                }
                break;
            case R.id.iv_login_black:
                finish();
                break;
            case R.id.iv_login_weibo:
                Toast.makeText(this, "点击", Toast.LENGTH_SHORT).show();
                LoginWeiBo();
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
    }

    private void LoginWeiBo() {
        //第三方登录
        UMShareAPI.get(this).getPlatformInfo(this, SHARE_MEDIA.SINA, this);
    }


    @Override
    public void onStart(SHARE_MEDIA share_media) {

    }

    @Override
    public void onComplete(SHARE_MEDIA share_media, int i, Map<String, String> map) {
        //微博第三方登录
        String id = map.get("id");
        String screen_name = map.get("screen_name");
        DBService.getDbService().delete("User", null, null);
        //存入数据库
        ContentValues values = new ContentValues();
        values.put("nick_name", id);
        values.put("user_name", screen_name);
        values.put("user_pwd", "123456");
        long user = DBService.getDbService().insert("User", values);
        if (user > 0) {
            Log.d("DBService", "数据库储存成功");
            Toast.makeText(this, "id" + id + "" + screen_name, Toast.LENGTH_SHORT).show();
            p.LoginRequest(screen_name, "123456");
            EventBus.getDefault().post(screen_name);
            SpUtils.getInstance().SpWrite(true);
            DBService.getDbService().close();
            finish();
        } else {
            Log.d("DBService", "数据库储存失败");
        }

    }

    @Override
    public void onError(SHARE_MEDIA share_media, int i, Throwable throwable) {
        Log.e("", "onError:" + throwable.getMessage());
        Log.e("", "onError:" + throwable.getLocalizedMessage());
    }

    @Override
    public void onCancel(SHARE_MEDIA share_media, int i) {

    }
}
